package com.watson.nio;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @program: mytest
 * @description:
 * @author: zhangpeng348@jd.com
 * @date: 2019-04-07 17:38
 **/
public class TestChannel {


    public void getChannel() {
        try {
            RandomAccessFile aFile = new RandomAccessFile("./nio-data.txt", "rw");
            FileChannel inChannel = aFile.getChannel();

            ByteBuffer buf = ByteBuffer.allocate(48);

            int bytesRead = inChannel.read(buf);
            while (bytesRead != -1) {

                System.out.println("Read " + bytesRead);
                buf.flip();

                while(buf.hasRemaining()){
                    System.out.print((char) buf.get());
                }

                buf.clear();
                bytesRead = inChannel.read(buf);
            }
            aFile.close();
        } catch (Exception e) {

        }
    }

    public static void main(String[] args) {
        TestChannel testChannel = new TestChannel();
        testChannel.getChannel();
    }
}
